<?php
  defined('_JEXEC') or die();
  jimport('joomla.application.component.model');
  require_once('base.php');
  
  class TeamGameStatModelTeamGameStat extends BaseModel
  {     
    var $_name = "teamgamestat";
    var $_table = "#__pbny_team_game_stats";
    
    function get_list_summary($id = null){
      
      $t_schedule = '#__pbny_schedules';
      $t_team     = '#__pbny_teams';
      
      $sql = 'SELECT tgs.*, s.schedule, t.name as team ' .
           'FROM ' . $this->_table . ' tgs ' .
           "LEFT JOIN $t_schedule s ON s.id=tgs.schedule_id ".
           "LEFT JOIN $t_team t ON t.id=tgs.team_id ";
      
      $where = null;
      if($id)
        $where = ' WHERE id = ' . $id;
      
      $this->_sql = $sql;
          
      return $this->getListData();
    }
    
    function get_by_team_id($team_id){
    
      $sql = 'SELECT * ' .
             'FROM '.$this->_table .
           " WHERE team_id = $team_id";
    
      return $this->_get($sql);
    }
    
    function get_by_schedule_id($schedule_id){
      
      $sql = 'SELECT * ' .
           'FROM '.$this->_table.
           " WHERE schedule_id = $schedule_id";
      
      return $this->_get($sql);
    }
    
    function get_winner_by_schedule_id($schedule_id){
    
      $schedules = $this->get_by_schedule_id($schedule_id);
      $score = 0;
      $index = 0;
      
      if(empty($schedules))
        return null;
      
      for($i = 0; $i < count($schedules); $i++){
        if($score < $schedules[$i]->final_score){
          $score = $schedules[$i]->final_score;
        $index = $i;
        }
      }
      
      return $schedules[$index];
    }
    
    function get_avg_season_stats($team_id, $season_id){
    
      $result = array();
      $stats = $this->get_season_stats_by_team_id($team_id, $season_id);
      if(!$stats)
        return $result;
        
      $result['final_score']  = 0;
      $result['is_overtime']  = 0;
      $result['field_goals']  = 0;
      $result['three_points']  = 0;
      $result['free_throws']  = 0;
      $result['off_rebounds']  = 0;
      $result['def_rebounds']  = 0;
      $result['assists']    = 0;
      $result['steals']    = 0;
      $result['blocks']    = 0;
      
      foreach($stats as $stat){
        $result['final_score']   += $stat->final_score;
        if($stat->is_overtime)
          $result['is_overtime'] += 1;
        $result['field_goals']    += $stat->field_goals;
        $result['three_points']   += $stat->three_points;
        $result['free_throws']    += $stat->free_throws;
        $result['off_rebounds']   += $stat->off_rebounds;
        $result['def_rebounds']   += $stat->def_rebounds;
        $result['assists']     += $stat->assists;
        $result['steals']     += $stat->steals;
        $result['blocks']     += $stat->blocks;
      }
      
      $games      = count($stats);
      foreach($result as $key=>$value)
        $result["avg_$key"] = number_format($value/$games, 2);
      
      $result['games_played'] = $games;
      return $result;
    }
    
    function get_opponent_avg_season_stats($team_id, $season_id){
    
      // Opposite for get_avg_season_stats
      $result     = array();
      $team_stats = $this->get_season_stats_by_team_id($team_id, $season_id);
      $sched_ids  = array();
      foreach($team_stats as $stat)
        array_push($sched_ids, $stat->schedule_id);
      
      $sql = 'SELECT * '.
           "FROM $this->_table ".
           'WHERE schedule_id in ('.implode(',', $sched_ids).
           ") AND team_id!=$team_id";
      $stats = $this->_get($sql);
      
      $result['final_score']  = 0;
      $result['is_overtime']  = 0;
      $result['field_goals']  = 0;
      $result['three_points']  = 0;
      $result['free_throws']  = 0;
      $result['off_rebounds']  = 0;
      $result['def_rebounds']  = 0;
      $result['assists']    = 0;
      $result['steals']    = 0;
      $result['blocks']    = 0;
      foreach(array_keys($result) as $key)
        $result["avg_$key"] = 0;
      $result['games_played'] = 0;
      
      if(!$stats)
        return $result;
      
      foreach($stats as $stat){
        $result['final_score']   += $stat->final_score;
        if($stat->is_overtime)
          $result['is_overtime'] += 1;
        $result['field_goals']    += $stat->field_goals;
        $result['three_points']   += $stat->three_points;
        $result['free_throws']    += $stat->free_throws;
        $result['off_rebounds']   += $stat->off_rebounds;
        $result['def_rebounds']   += $stat->def_rebounds;
        $result['assists']     += $stat->assists;
        $result['steals']     += $stat->steals;
        $result['blocks']     += $stat->blocks;
      }
      
      $games      = count($stats);
      foreach($result as $key=>$value)
        $result["avg_$key"] = number_format($value/$games,2);
      
      $result['games_played'] = $games;
      return $result;
    }
    
    function get_season_stats_by_team_id($team_id, $season_id){
      /*
      SELECT tgs.*,sd.*
      FROM jos_pbny_team_game_stats tgs
      LEFT JOIN jos_pbny_schedules s ON s.id = tgs.schedule_id
      LEFT JOIN jos_pbny_division_conferences dc on dc.conference_id = s.conference_id
      LEFT JOIN jos_pbny_season_divisions sd on sd.division_id = dc.division_id
      LEFT JOIN jos_pbny_seasons ss on ss.id = sd.season_id
      WHERE s.schedule>=ss.start_date and s.schedule<=ss.end_date
      and tgs.team_id=<team_id> and sd.season_id=<season_id>
      */
      
      $sql = 'SELECT tgs.* '.
           "FROM $this->_table tgs ".
           'LEFT JOIN #__pbny_schedules s ON s.id = tgs.schedule_id '.
           'LEFT JOIN #__pbny_division_conferences dc on dc.conference_id = s.conference_id '.
           'LEFT JOIN #__pbny_season_divisions sd on sd.division_id = dc.division_id '.
           'LEFT JOIN #__pbny_seasons ss on ss.id = sd.season_id '.
           'WHERE s.schedule>=ss.start_date '.
           ' AND s.schedule<=ss.end_date'. 
           " AND sd.season_id=$season_id ".
           " AND tgs.team_id=$team_id ";
        
      return $this->_get($sql);
    }
    
    function get_season_stats($season_id){
      $sql = 'SELECT tgs.* '.
           "FROM $this->_table tgs ".
           'LEFT JOIN #__pbny_schedules s ON s.id = tgs.schedule_id '.
           'LEFT JOIN #__pbny_division_conferences dc on dc.conference_id = s.conference_id '.
           'LEFT JOIN #__pbny_season_divisions sd on sd.division_id = dc.division_id '.
           'LEFT JOIN #__pbny_seasons ss on ss.id = sd.season_id '.
           'WHERE s.schedule>=ss.start_date '.
           ' AND s.schedule<=ss.end_date'. 
           " AND sd.season_id=$season_id ";
           
      return $this->_get($sql);
    }
    
    # this method should be revised and changed, because its ugly
    function get_season_standings($season_id){
      
      /*
      #get season stats
      $stats = $this->get_season_stats_by_team_id($team_id, $season_id);
      
      if(!$stats)
        return null;
      
      #get schedule_ids related to team_id
      $schedule_ids = array();
      foreach($stats as $s)
        array_push($schedule_ids, $s->schedule_id);
      */
      #get stats with schedule_ids and season_ids
      $sql = 'SELECT tgs.* '.
           "FROM $this->_table tgs ".
           'LEFT JOIN #__pbny_schedules s ON s.id = tgs.schedule_id '.
           'LEFT JOIN #__pbny_division_conferences dc on dc.conference_id = s.conference_id '.
           'LEFT JOIN #__pbny_season_divisions sd on sd.division_id = dc.division_id '.
           'LEFT JOIN #__pbny_seasons ss on ss.id = sd.season_id '.
           'WHERE s.schedule BETWEEN ss.start_date AND ss.end_date '.
           " AND sd.season_id=$season_id ";

      $stats  =  $this->_get($sql);
      if(!$stats)
        return $stats;
      
      $result      = array();
      $team_result = array('wins' => 0, 'loss' => 0, 'gb' => 0, 'pmade' => 0,
                      'palwd'=> 0, 'l3' => '', 'streak' => 0, 'gp' => 0);
      $l3           = array();
      $gb_team     = array();
      $data        = array();
      $palwd       = array();
        
      foreach($stats as $stat){
      
        if(!isset($data[$stat->schedule_id]))
          $data[$stat->schedule_id] = array();
        
        $data[$stat->schedule_id][$stat->team_id] = $stat;
        
        if(!isset($l3[$stat->team_id]))
          $l3[$stat->team_id] = array();
          
        if(!isset($gb_team[$stat->team_id]))
          $gb_team[$stat->team_id] = 0;
        
        if(!isset($result[$stat->team_id])){
          $result[$stat->team_id] = array('wins' => 0, 'loss' => 0, 'gb' => 0, 'pmade' => 0,
          'palwd'=> 0, 'l3' => '', 'streak' => 0, 'gp' => 0, 'diff' => 0);
        }
        
        #if two game stats
        if(count($data[$stat->schedule_id]) > 1){
        
          $palwd = array();
          
          #decide who won the game
          $win_team  = 0;
          $win_score = 0;
          foreach($data[$stat->schedule_id] as $team_id => $s){

            $result[$team_id]['gp'] += 1; #gp
            $result[$team_id]['pmade'] += $s->final_score; #pmade
            
            if(!isset($palwd[$team_id]))
              $palwd[$team_id] = 0;
            $palwd[$team_id] += $s->final_score; #palwd
            
            if($win_score == 0){
            
              $win_score = $s->final_score;
              $win_team  = $s->team_id;
              
            }elseif($win_score < $s->final_score){
            
              $result[$win_team]['loss'] += 1;  #loss
              array_push($l3[$win_team], 0);
              
              if($result[$win_team]['streak'] <= 0)  #streak
                $result[$win_team]['streak'] -= 1;
              elseif($result[$win_team]['streak'] > 0)
                $result[$win_team]['streak'] = -1;
              
              $win_score = $s->final_score;
              $win_team  = $s->team_id;
            
            }elseif($win_score > $s->final_score){
            
              $result[$team_id]['loss'] += 1;  #loss
              array_push($l3[$team_id], 0);
              
              if($result[$team_id]['streak'] <= 0)  #streak
                $result[$team_id]['streak'] -= 1;
              elseif($result[$team_id]['streak'] > 0)
                $result[$team_id]['streak'] = -1;
            }
          }
          
          #points allowed
          foreach(array_keys($palwd) as $tid){
            foreach($palwd as $id => $score){
            
              if($id != $tid)
                $result[$tid]['palwd'] += $score;
                
            }
          }
          
          if($win_team){
          
            $result[$win_team]['wins'] += 1; #wins
            array_push($l3[$win_team], 1);
            
            if($result[$win_team]['streak'] >= 0)  #streak
              $result[$win_team]['streak'] += 1;
            elseif($result[$win_team]['streak'] < 0)
              $result[$win_team]['streak'] = 1;
              
          }
          
          $gb_team[$win_team] += 1;
          
        }
      }
      
      #format L3
      foreach($l3 as $team_id => $l){
      
        $str_l3 = array('w'=>0, 'l'=>0);
      
        for($i=2; $i>=0; $i--){
          if(!isset($l3[$team_id][$i]))
            continue;
          if($l3[$team_id][$i] > 0)
            $str_l3['w'] += 1;
          elseif(($l3[$team_id][$i] == 0) && isset($l3[$team_id][$i]))
            $str_l3['l'] += 1;
        }
        $result[$team_id]['l3'] = $str_l3['w'].'W '.$str_l3['l'].'L';
        
      }
      
      #gb
      arsort($gb_team);
      $base = reset($gb_team);
      foreach($gb_team as $key => $value)
        $gb_team[$key] = abs($value - $base);
      
      #format other results
      foreach($result as $team_id => $r){
        if($r['loss'] == 0)
          $r['pct'] = 100;
        else
          $r['pct'] = number_format($r['wins']/$r['loss'], 2);
        
        $r['diff']    = $r['pmade'] - $r['palwd'];
        
        if($r['streak'] < 0) #streak again //format
          $r['streak'] = abs($r['streak']).'L';
        elseif($r['streak'] > 0)
          $r['streak'] = $r['streak'].'W';
        
        $r['gb'] = $gb_team[$team_id];
        $result[$team_id] = $r;
      }
      
      return $result;
    
    }
    
  }
?>